﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DataPersonalization.Utis
{
    public class MyUtis
    {
        /// <summary>
        /// Ghi log từng link xuống file json
        /// </summary>
        /// <param name="message"></param>
        public void TraceLog_Status(Links obj, string fileName)
        {
            try
            {
                string pathFolder = @"Logs\";
                if (!Directory.Exists(pathFolder))
                {
                    Directory.CreateDirectory(pathFolder);
                }

                pathFolder = @"Logs\LinkError";
                if (!Directory.Exists(pathFolder))
                {
                    Directory.CreateDirectory(pathFolder);
                }

                #region làm việc với file
                string pathFile = pathFolder + "/" + fileName;

                if (!File.Exists(pathFile))
                {
                    File.Create(pathFile).Dispose();
                }
                #endregion

                #region Thực hiện ghi file

                FileStream fsObj = new FileStream(pathFile, FileMode.Append);
                StreamWriter swObj = new StreamWriter(fsObj, Encoding.UTF8);

                string mes = obj.No.ToString() + ";" + obj.Id + ";" + obj.Link + ";" + obj.Status;

                // Ghi từng dòng
                swObj.WriteLine(mes);

                swObj.Flush();

                swObj.Close();
                fsObj.Close();

                #endregion
            }
            catch (Exception ex) { }
        }

        public void WriteLink(string fileName, int stt, string id, string link)
        {
            try
            {
                string pathFolder = @"Files/";
                if (!Directory.Exists(pathFolder))
                {
                    Directory.CreateDirectory(pathFolder);
                }

                #region làm việc với file
                string pathFile = pathFolder + "/" + fileName;

                if (!File.Exists(pathFile))
                {
                    File.Create(pathFile).Dispose();
                }
                #endregion

                #region Thực hiện ghi file

                FileStream fsObj = new FileStream(pathFile, FileMode.Append);
                StreamWriter swObj = new StreamWriter(fsObj, Encoding.UTF8);

                string mes = stt + ";" + id.ToString() + ";" + link;

                // Ghi từng dòng
                swObj.WriteLine(mes);

                swObj.Flush();

                swObj.Close();
                fsObj.Close();

                #endregion
            }
            catch (Exception ex) { }
        }

        public void TraceLog_Total(int total, int tSuccess, int tFalse)
        {
            try
            {
                string pathFolder = @"Logs\";
                if (!Directory.Exists(pathFolder))
                {
                    Directory.CreateDirectory(pathFolder);
                }

                #region làm việc với file
                string pathFile = pathFolder + "/total.txt";

                if (!File.Exists(pathFile))
                {
                    File.Create(pathFile).Dispose();
                }
                #endregion

                #region Thực hiện ghi file

                FileStream fsObj = new FileStream(pathFile, FileMode.Create);
                StreamWriter swObj = new StreamWriter(fsObj, Encoding.UTF8);

                string mes = total.ToString() + ";" + tSuccess.ToString() + ";" + tFalse.ToString();

                // Ghi từng dòng
                swObj.WriteLine(mes);

                swObj.Flush();

                swObj.Close();
                fsObj.Close();

                #endregion
            }
            catch (Exception ex) { }
        }

        public int GetTotal()
        {
            try
            {
                string pathFile = @"Logs\total.txt";
                if (!File.Exists(pathFile))
                {
                    return 0;
                }

                StringBuilder sb = new StringBuilder();
                using (StreamReader sr = new StreamReader(pathFile))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] arrValue = line.Split(';');
                        return Convert.ToInt32(arrValue[0]);
                    }
                }

            }
            catch { }
            return 0;
        }

        public int GetTotalSuccess()
        {
            try
            {
                string pathFile = @"Logs\total.txt";
                if (!File.Exists(pathFile))
                {
                    return 0;
                }

                StringBuilder sb = new StringBuilder();
                using (StreamReader sr = new StreamReader(pathFile))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] arrValue = line.Split(';');
                        return Convert.ToInt32(arrValue[1]);
                    }
                }

            }
            catch { }
            return 0;
        }

        public int GetTotalFalse()
        {
            try
            {
                string pathFile = @"Logs\total.txt";
                if (!File.Exists(pathFile))
                {
                    return 0;
                }

                StringBuilder sb = new StringBuilder();
                using (StreamReader sr = new StreamReader(pathFile))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] arrValue = line.Split(';');
                        return Convert.ToInt32(arrValue[2]);
                    }
                }
            }
            catch { }
            return 0;
        }

        public List<Links> GetListLinksError()
        {
            try
            {
                string path = @"Logs\LinkError\";
                if (!Directory.Exists(path))
                {
                    return null;
                }

                var directory = new DirectoryInfo(path);
                string fileName = (from f in directory.GetFiles() orderby f.LastWriteTime descending select f).First().ToString();

                if (!File.Exists(path + fileName))
                {
                    return null;
                }

                List<Links> ls = new List<Links>();
                StringBuilder sb = new StringBuilder();

                using (StreamReader sr = new StreamReader(path + fileName))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] arrValue = line.Split(';');

                        Links obj = new Links();

                        obj.No = Convert.ToInt32(arrValue[0]);
                        obj.Id = arrValue[1];
                        obj.Link = arrValue[2];
                        obj.Status = arrValue[3];

                        ls.Add(obj);
                    }
                }

                return ls;
            }
            catch
            {
                return null;
            }
        }

        public List<DomainEntity> GetListDomainError()
        {
            try
            {
                string path = @"Logs\LinkError\";
                if (!Directory.Exists(path))
                {
                    return null;
                }

                string[] arr = Directory.GetFiles(path);

                if (arr.Length > 0)
                {
                    List<DomainEntity> ls = new List<DomainEntity>();
                    int no = 1;

                    for (int i = 0; i < arr.Length; i++)
                    {
                        if (File.Exists(arr[i]))
                        {
                            StringBuilder sb = new StringBuilder();

                            using (StreamReader sr = new StreamReader(arr[i]))
                            {
                                String line;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    string[] arrValue = line.Split(';');
                                    if (arrValue.Length > 0)
                                    {
                                        string domain;
                                        if (arrValue[2].Contains("http://"))
                                        {
                                            domain = arrValue[2].Split('/')[0] + "//" + arrValue[2].Split('/')[2];
                                        }
                                        else
                                        {
                                            domain = arrValue[2].Split('/')[0];
                                        }

                                        DomainEntity obj = new DomainEntity();

                                        obj.No = no;
                                        obj.Domain = domain;
                                        obj.Note = arrValue[3];

                                        // kiểm tra domain có trong list chưa
                                        bool existed = ls.Exists(e => e.Domain == domain);

                                        if (existed == false)
                                        {
                                            ls.Add(obj);

                                            no = no + 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return ls;
                }
            }
            catch { }
            return null;
        }

        public void DeleteFileLogTotal()
        {
            try
            {
                string pathFile = @"Logs\total.txt";
                if (File.Exists(pathFile))
                {
                    File.Delete(pathFile);
                }
            }
            catch { }
        }

        public void DeleteFileLogStatus()
        {
            try
            {
                string patt = @"Logs\LinkError\";
                if (Directory.Exists(patt))
                {
                    string[] arrFile = Directory.GetFiles(patt);

                    if (arrFile.Length > 0)
                    {
                        for (int i = 0; i < arrFile.Length; i++)
                        {
                            if (File.Exists(arrFile[i]))
                            {
                                File.Delete(arrFile[i]);
                            }
                        }
                    }
                }

            }
            catch { }
        }

        public List<Links> GetListLinksFromFile(string fileName)
        {
            List<Links> ls = new List<Links>();

            string pathFile = fileName;
            if (!File.Exists(pathFile))
            {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(pathFile))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] arrValue = line.Split(';');

                    Links obj = new Links();

                    obj.Id = arrValue[1];
                    obj.Link = arrValue[2];

                    ls.Add(obj);
                }
            }

            return ls;
        }
    }
}
